package com.tarena.csmall.seckill.service;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillCommitVO;
import cn.tedu.mall.pojo.seckill.vo.SeckillSpuVO;
import com.alibaba.fastjson.JSON;
import com.tarena.csmall.seckill.checker.SeckillCommitChecker;
import java.time.LocalDateTime;
import java.util.List;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
public class SeckillCommitService {
    //当容器中存在多个同一个接口类对象bean时
    //可以在bean类上添加Order注解,可以指定List封装顺序 越小 index越靠前
    @Autowired
    private List<SeckillCommitChecker> checkers;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    //代码优化目的,在service方法中集中处理的是业务,而不是细节
    public SeckillCommitVO commitSeckill(SeckillOrderAddDTO dto, String randCode) {
        //1.验证 具体验证细节,交给实现类
        commitCheck(dto,randCode);
        //5. 发送消息
        //使用rocketmqTempalte调用api 将订单数据发送到队列
        Message message= MessageBuilder.withPayload(dto).build();
        rocketMQTemplate.send("seckill_order_topic",message);
        //6. 返回结果
        SeckillCommitVO seckillCommitVO=new SeckillCommitVO();
        seckillCommitVO.setPayAmount(dto.getAmountOfActualPay());
        seckillCommitVO.setSn(dto.getSn());
        seckillCommitVO.setCreateTime(LocalDateTime.now());
        return seckillCommitVO;
    }

    private void commitCheck(SeckillOrderAddDTO dto, String code) {
        for (SeckillCommitChecker checker : checkers) {
            checker.check(dto,code);
        }
    }
}
